package org.liangguo.ktpref

import java.io.File


/**
 * @author ldh
 * 时间: 2022/10/27 16:38
 * 邮箱: 2637614077@qq.com
 */
class KtPref(val group: String, initRoot: File? = null) {

    /**
     * [KtPref]当前储存文件的目录
     */
    var fileDir: File = File("")
        private set

    fun initialize(root: File) {
        fileDir = File(root, "KtPref/$group")
        fileDir.mkdirs()
    }

    init {
        initRoot?.let { initialize(it) }
    }

    fun put(key: String, value: String) {
        File(fileDir, key).apply {
            createNewFile()
        }.writeText(value)
    }

    fun put(key: String, value: Int) {
        put(key, value.toString())
    }

    fun put(key: String, value: Boolean) {
        put(key, value.toString())
    }

    fun put(key: String, value: Float) {
        put(key, value.toString())
    }

    fun put(key: String, value: Double) {
        put(key, value.toString())
    }

    fun getString(key: String): String? {
        val file = File(fileDir, key)
        return if (file.exists() && file.isFile) {
            file.readText()
        } else null
    }

    fun getString(key: String, default: String) = getString(key) ?: default


    fun getBoolean(key: String) = getString(key)?.toBooleanStrictOrNull()

    fun getBoolean(key: String, default: Boolean) = getBoolean(key) ?: default

    fun getInt(key: String) = getString(key)?.toIntOrNull()

    fun getInt(key: String, default: Int) = getInt(key) ?: default

    fun getDouble(key: String) = getString(key)?.toDoubleOrNull()

    fun getDouble(key: String, default: Double) = getDouble(key) ?: default

    fun getFloat(key: String) = getString(key)?.toFloatOrNull()

    fun getFloat(key: String, default: Float) = getFloat(key) ?: default


    companion object {
        val default = KtPref("default")

        fun initialize(root: File) {
            default.initialize(root)
        }
    }


}